package com.aiju.cash.ui.enter;

import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.app.config.ConfigManager;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.JsonData;
import com.aiju.cash.R;
import com.aiju.cash.core.api.EnterApi;
import com.aiju.cash.core.api.EnterImageApi;
import com.aiju.cash.util.ImageDialogUtil;
import com.aiju.cash.util.ImageSelectorHelper;
import com.aiju.common.image.AiJuImageLoaderProxy;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.dialog.ListDialog;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.common.Constant;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.aiju.cash.ui.good.GoodAddActivity.REQUEST_CODE;

/**
 * @author: 佐为
 * @date: 2017-05-26 09:47
 * @version: V1.0
 * @Description: 门头照与内景照
 */
public class HeaderImageActivity extends BaseTitleActivity {

    private GridView mGridView;
    private ImageView imageView;
    private MyBaseAdapter myBaseAdapter;

    private List<String> files = new ArrayList<>();
    private LinkedList<String> paths = new LinkedList<>();

    private String carmerPath;

    private Map<String, String> imageMap = new HashMap<>();

    private boolean remove;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_header);
        setCenterTitle("门头照与内景照");
        setRightTitle("确认上传");
        paths.add("add");

        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (paths.size()<4){
                    T.ToastShort("请选择至少3张以上的门头照和内景图");
                    return;
                }
                if (!Util.isEmpty(files)) {
                    for (int i = 0; i < files.size(); i++) {
                        final String filePath = files.get(i);
                        mDialogHelper.showLoadingProgressDialog();
                        new EnterImageApi().uploadShopImage(ConfigManager.getInstance().getUser().getToken(), new File(filePath), new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (files.isEmpty()) {
                                    mDialogHelper.dismissProgressDialog();
                                }
                                files.remove(filePath);
                                T.ToastNetError();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                files.remove(filePath);
                                JsonData jsonData = new JsonData(response);
                                if (jsonData.isSuccess()) {
                                    imageMap.put(filePath, jsonData.getData().toString());
                                }

                                if (files.isEmpty()) {
                                    T.ToastShort("上传完成");
                                    onResult();
                                }
                            }
                        });
                        L.d("上传图片地址：" + filePath);
                    }
                } else if (remove) {
                    onResult();
                } else {
                    T.ToastShort("请选择图片");
                }
            }
        });
        mGridView = (GridView) findViewById(R.id.gv_store_header);
        imageView = (ImageView) findViewById(R.id.iv_enter_add);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPic();
            }
        });

        if (!Util.isEmpty(getIntent().getStringExtra("image_id"))) {
            imageView.setVisibility(View.GONE);
            mGridView.setVisibility(View.VISIBLE);
            new EnterApi(mDialogHelper).getImageInfo(getIntent().getStringExtra("image_id"), new SimpleHttpCallback() {
                @Override
                protected void onDataSuccess(String data) {
                    String[] image = data.split(",");
                    for (int i = 0; i < image.length; i++) {
                        String[] split = image[i].split("分割线");
                        paths.addFirst(split[1]);
                        imageMap.put(split[1], split[0]);
                    }
                    myBaseAdapter = new MyBaseAdapter();
                    mGridView.setAdapter(myBaseAdapter);
                }
            });
        }
    }

    /**
     * 返回图片id
     */
    private void onResult() {
        StringBuilder sb = new StringBuilder();
        Iterator iter = imageMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            sb.append("," + entry.getValue());
        }
        Intent intent = new Intent();
        intent.putExtra("data", sb.toString().replaceFirst(",", ""));
        setResult(200, intent);
        finish();
    }

    /**
     * 选择图片
     */
    private void showPic() {
        if (paths.size() == 11) {
            T.ToastShort("最多可选择10张图片");
            return;
        }
        ImageDialogUtil.showSelectPicDialog(HeaderImageActivity.this, new ListDialog.OnItemOnClick() {
            @Override
            public void click(String item, int position) {
                if (item.equals("拍照")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 启动系统相机
                    startActivityForResult(intent, ImageDialogUtil.REQUEST_CAMERA_1);
                } else {
                    new ImageSelectorHelper().openMultiImageSelector(HeaderImageActivity.this, 10 - paths.size() + 1 + files.size(), REQUEST_CODE);
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Constant.imageList.clear();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片选择结果回调
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> list = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
            for (String path : list) {
                if (!files.contains(path)) {
                    paths.addFirst(path);
                    files.add(path);
                }
            }//拍照
        } else if (requestCode == ImageDialogUtil.REQUEST_CAMERA_1 && resultCode == RESULT_OK && data != null) {
            carmerPath = ImageDialogUtil.saveCameraImage(data);
            paths.addFirst(carmerPath);
            files.add(carmerPath);
        }

        if (paths.size() > 0) {
            imageView.setVisibility(View.GONE);
            mGridView.setVisibility(View.VISIBLE);
            if (myBaseAdapter == null) {
                myBaseAdapter = new MyBaseAdapter();
                mGridView.setAdapter(myBaseAdapter);
            } else {
                myBaseAdapter.notifyDataSetChanged();
            }
        }
    }

    private class MyBaseAdapter extends BaseAdapter {

        public MyBaseAdapter() {
            if (!paths.contains("add")) {
                paths.add("add");
            }
        }

        @Override
        public int getCount() {
            return paths.size();
        }

        @Override
        public Object getItem(int position) {
            return paths.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View inflate = LayoutInflater.from(HeaderImageActivity.this).inflate(R.layout.item_header_imge, parent, false);
            ImageView header = (ImageView) inflate.findViewById(R.id.iv_header_item);
            final String path = paths.get(position);
            if (path.equals("add")) {
                inflate.findViewById(R.id.iv_header_close).setVisibility(View.GONE);
                header.setImageResource(R.mipmap.ic_header_add);
                header.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showPic();
                    }
                });
            } else {
                AiJuImageLoaderProxy.getInstance().displayImage(paths.get(position), header, -1);
                inflate.findViewById(R.id.iv_header_close).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        paths.remove(path);
                        files.remove(path);
                        notifyDataSetChanged();
                        if (paths.size() == 1) {
                            imageView.setVisibility(View.VISIBLE);
                            mGridView.setVisibility(View.GONE);
                        }
                        if (path.equals(carmerPath)) {
                            carmerPath = "";
                        } else {
                            Constant.imageList.remove(path);
                        }
                        if (imageMap.containsKey(path)) {
                            remove = true;
                            imageMap.remove(path);
                        }
                    }
                });
            }
            return inflate;
        }
    }
}
